package com.lft.examsys.util;

import com.lft.examsys.exception.ValidationFailureException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ：Qingchen
 * @date ：Created in 2022/3/28 19:37
 * @description：文件上传
 * @modified By：
 * @version: $
 */
public class FileUtil {

    public static String uploadFile(MultipartFile file, HttpServletRequest request, String path) throws ValidationFailureException {
        if (!path.endsWith("/"))
            path += "/";
        String realPath = request.getRealPath(path);
        File dir = new File(realPath);
        if (!dir.exists() && !dir.mkdir()) {
            throw new ValidationFailureException("can't make dir");
        }
        String filename = file.getOriginalFilename() + UUID.randomUUID();
        realPath += filename;
        try {
            file.transferTo(new File(realPath));
        } catch (IOException e) {
            throw new ValidationFailureException("Can't not save this file");
        }
        return path + filename;
    }
}
